package tgc.edu.ljc.web.controller;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import tgc.edu.ljc.entity.SysRole;
import tgc.edu.ljc.entity.SysUser;
import tgc.edu.ljc.repository.RoleRepository;
import tgc.edu.ljc.repository.SysUserRepository;
import tgc.edu.ljc.security.UserUtils;

@Controller
public class MainController {
	@Autowired
	private SysUserRepository userDAO;
	@Autowired
	private UserUtils userUtils;
	@Autowired
	private RoleRepository roleDAO;
	
	@RequestMapping(value="/main")
	public String main() {
		return "main";
	}
	
	@RequestMapping(value="/login",method=RequestMethod.GET)
	public String gotoLogin() {
		List<SysRole> roles = roleDAO.findAll();
		if(roles.isEmpty()) {
			SysRole role=new SysRole();
			role.setCode("ROLE_ADMIN");
			role.setName("管理员");
			roleDAO.save(role);
			SysRole role2=new SysRole();
			role2.setName("学生");
			role2.setCode("ROLE_STUDENT");
			roleDAO.save(role2);
			SysUser user=new SysUser();
			user.setName("管理员");
			BCryptPasswordEncoder encoder=new BCryptPasswordEncoder();
			user.setPassword(encoder.encode("admin"));
			user.setUsername("admin");
			user.getRoles().add(role);
			userDAO.save(user);
		}
		return "login";
	}
	
	@RequestMapping(value="/changePassword",method=RequestMethod.GET)
	public String gotoChangePassword() {
		return "changePassword";
	}
	
	@RequestMapping(value="/changePassword",method=RequestMethod.POST)
	public String changePassowrd(String oldPwd,String newPwd) {
		SysUser user = userUtils.getUser();
		BCryptPasswordEncoder encoder=new BCryptPasswordEncoder();
		if(encoder.matches(oldPwd, user.getPassword())) {
			user.setPassword(encoder.encode(newPwd));
			userDAO.save(user);
		}
		return "redirect:login";
	}
}
